package com.sport.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import com.sport.model.Result;
import com.sport.utils.FileUtils;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.SneakyThrows;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.Paths;
import java.util.UUID;

/**
 * 文件上传控制器
 * @author: 开心摆烂
 * @date : 2024-11-20
 */
@SaIgnore
@RestController
@Tag(name = "文件上传")
@RequestMapping("/common")
public class CommonController {

    @PostMapping("/upload")
    public Result<String> upload(@RequestBody MultipartFile file){
        return Result.success("文件上传成功！", FileUtils.upload(file));
    }

    @SneakyThrows
    @GetMapping("/view/{filename}")
    public void getImage(@PathVariable String filename, HttpServletResponse response){
        String contextType = this.getContextType(filename);
        response.setContentType(contextType);
        //使用ServletOutputStream写入图片数据（1.获取输出流2.得到文件流）
        try (ServletOutputStream out = response.getOutputStream();
             InputStream in = new BufferedInputStream(new FileInputStream(FileUtils.path+filename))){
            if (contextType.equals("video/mp4")){
                response.setContentLength(in.available());
            }
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        }
    }


    /**
     * 根据文件名生成时间文件名
     * @author: 开心摆烂
     * @date : 2024-11-20
     */

    private String filename(String fileName){
        //规则：1.UU重复率小（UUID.randomUUID()）2.时间戳重复几率0，但是会有线程问题（system.currentTimeMILLIS()）
        return UUID.randomUUID()+fileName.substring(fileName.lastIndexOf("."));
    }

        private  String getContextType(String filename){
            String sufi = filename.substring(filename.lastIndexOf(".")+1);
            return switch (sufi){
                case "png" , "PNG" -> MediaType.IMAGE_PNG_VALUE;
                case "jpg" , "jpeg","JPG","JPEG"-> MediaType.IMAGE_JPEG_VALUE;
                case "gif" , "GIF" -> MediaType.IMAGE_GIF_VALUE;
                case "mp4" , "MP4" -> "video/mp4";
                default -> MediaType.APPLICATION_JSON_VALUE;
            };
    }
}
